'use strict';
var express = require('express');
var timeout = require('connect-timeout');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var AV = require('leanengine');
require('body-parser-xml')(bodyParser);

//短信、用户
var api_sms   = require('./routes/api_sms');
var api_users = require('./routes/api_user');
var api_group = require('./routes/api_group');
var api_model = require('./routes/api_model');
var api_module = require('./routes/api_imgmodule');
var api_fileup = require('./routes/api_fileup');
var api_request = require('./routes/api_request');
var api_test = require('./routes/api_test');

var app = express();

// 设置模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(express.static('public'));

// 设置默认超时时间
app.use(timeout('30s'));

app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

app.enable('trust proxy');
// 需要重定向到 HTTPS 可去除下一行的注释。

app.use(cookieParser());
app.use(bodyParser.xml());
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Token,token,X-Requested-With');
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Expose-Headers", "*");
    next();
});

app.get('/datamax', function(req, res) {
  res.render('index', { currentTime: new Date() });
});
app.get('/mymobile', function(req, res) {
  res.render('index', { currentTime: new Date() });
});




// 可以将一类的路由单独保存在一个文件中
app.use('/api_sms', api_sms);
app.use('/api_users',api_users);
app.use('/api_group',api_group);
app.use('/api_model',api_model);
app.use('/api_module',api_module);
app.use('/api_fileup',api_fileup);
app.use('/api_request',api_request);
app.use('/api_test',api_test);

app.use(function(req, res, next) {
  // 如果任何一个路由都没有返回响应，则抛出一个 404 异常给后续的异常处理器
  if (!res.headersSent) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
  }
});

// error handlers
app.use(function(err, req, res, next) {
  if (req.timedout && req.headers.upgrade === 'websocket') {
    // 忽略 websocket 的超时
    return;
  }

  var statusCode = err.status || 500;
  if (statusCode === 500) {
    console.error(err.stack || err);
  }
  if (req.timedout) {
    console.error('请求超时: url=%s, timeout=%d, 请确认方法执行耗时很长，或没有正确的 response 回调。', req.originalUrl, err.timeout);
  }
  res.status(statusCode);
  // 默认不输出异常详情
  var error = {};
  if (app.get('env') === 'development') {
    // 如果是开发环境，则将异常堆栈输出到页面，方便开发调试
    error = err;
  }
  res.render('error', {
    message: err.message,
    error: error
  });
});

module.exports = app;
